package club.jdiy.core;

import club.jdiy.admin.dao.DictItemDao;
import club.jdiy.admin.entity.Role;
import club.jdiy.admin.entity.User;
import club.jdiy.core.base.domain.DictInfo;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;
import java.util.Optional;

@Component
public class AdminContext extends HttpContext {
    /**
     * 获取当前登录到后台的用户
     *
     * @return user
     */
    public <T extends User> T getCurrentUser() {
        return (T) getRequest().getAttribute("CURRENT_USER");
    }

    /**
     * 判断当前用户是否有对目标资源的访问操作授权.
     * <br/>例如判断当前用户是否有商品添加的权限(假设商品管理菜单id=goods, 添加商品的按钮grantCode=add),则:<br/>
     * <pre>
     * if(adminContext.hasGrant("goods:add")){
     *       //do something
     * }
     * </pre>
     *
     * @param code 授权代码. 通常格式为:menuId  或者 menuId:grantCode
     * @return 有权限返回true, 无权返回false.
     */
    public boolean hasGrant(String code) {
        User user = getCurrentUser();
        return user != null && user.getRoleList() != null
                && user.getRoleList().stream().anyMatch(role -> role.getId() == 1 || //超管无条件true
                role.getGrantAuth() != null && role.getGrantAuth().contains("'" + code + "'"));
    }

    public Role hasRole(Integer roleId) {
        User user = getCurrentUser();
        return user.getRoleList() == null
                ? null
                : user.getRoleList().stream().filter(r -> r.getId().equals(roleId)).findFirst().orElse(null);
    }

    /**
     * 判断当前登录用户是否为开发者．
     * 若用户是超级管理员　且其用户名在　application.yml配置文件jdiy.developers中出现，　即为开发者
     *
     * @return 为开发者返回 true
     */
    public boolean isDeveloper() {
        User user = getCurrentUser();
        if (jDiyProperties.getDevelopers() == null || !jDiyProperties.getDevelopers().contains(user.getUid()))
            return false;
        return user.getRoleList().stream().anyMatch(r -> r.getId() == 1);
    }


    public Optional<Map<String, DictInfo>> getDict(String dictId) {
        return Optional.ofNullable(dictItemDao.get(dictId));
    }

    public Optional<DictInfo> getDict(String dictId, String value) {
        Map<String, DictInfo> m = getDict(dictId).orElse(null);
        return m == null ? Optional.empty() : Optional.ofNullable(m.get(value));
    }

    @Resource
    private DictItemDao dictItemDao;
}
